<template>
  <el-select
    v-model="selectvalue"
    :placeholder="placeholder"
    filterable
    v-bind="$attrs"
    collapse-tags
    class="elwidth"
    @change="changeFn"
    style="width: 100%"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="labelFormat(item)"
      :value="valueFormat(item)"
    >
    </el-option>
    <div style="padding: 5px" v-if="cacheValue">
      <el-button style="width: 100%" @click="queryFetch">获取最新</el-button>
    </div>
  </el-select>
</template>

<script>
import utils from "@/utils";

export default {
  props: {
    value: {
      required: true,
    },
    url: Function,
    payload: {
      type: Object|Array,
      default: () => {},
    },
    defaultOptions: {
      type: Array,
      default: () => [],
    },
    placeholder: String,
    cacheValue: String,
    labelFormat: {
      type: Function,
      default: (item) => {
        return item.name;
      },
    },
    valueFormat: {
      type: Function,
      default: (item) => {
        return item.code;
      },
    },
  },
  data() {
    return {
      selectvalue: this.value,
      options: [],
    };
  },
  watch: {
    value(newValue, oldValue) {
      this.selectvalue = newValue;
    },
    defaultOptions(newValue, oldValue) {
      this.options = newValue;
    },
  },
  mounted() {
    this.queryData();
  },
  methods: {
    queryData() {
      if (this.url) {
        // 从url获取
        let cacheValueData = utils.getsessionStorage(this.cacheValue); // 取缓存数据

        // 有缓存
        if (cacheValueData && cacheValueData.length > 0) {
          this.options = cacheValueData;
        } else {
          this.queryFetch();
        }
      } else {
        // 从defaultOptions获取
        this.options = this.defaultOptions;
      }
    },
    async queryFetch() {
      try {
        let { returnObj } = await this.url({
          ...this.payload,
          pageSize: 1000,
          pageNo: 1,
        });
        this.options = returnObj;

        if (this.cacheValue) {
          // 缓存请求的数据
          utils.setsessionStorage(this.cacheValue, returnObj);
        }
      } catch (error) {
        console.log(error);
      }
    },
    changeFn(val) {
      let row = {};
      this.options.map((item) => {
        if (val == this.valueFormat(item)) {
          row = { ...item };
        }
      });

      // change事件
      this.$emit("change", {
        value: val,
        row,
      });
      // 默认绑定事件
      this.$emit("input", this.selectvalue);
    },
  },
};
</script>

<style lang="scss" scoped></style>
